package com.tubruk.trackme;

import java.util.List;
import java.util.Locale;

import android.content.Context;
import android.content.Intent;
import android.location.Geocoder;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TableLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.Overlay;
import com.tubruk.database.DatabaseHelper;
import com.tubruk.database.TrackSummaryDB;
import com.tubruk.object.PopMenu;
import com.tubruk.object.TrackSummary;
import com.tubruk.util.dialog.ListMenu;

public class TrackMapActivity extends MapActivity {
	private static TrackMapActivity instance;
	
    private MyLocationListener locListener;
	
	//private ArrayList<PopMenu> options = null;
	
	//private static final int DIALOG_OPTIONS = 1;
    
    private static final int MENU_MAPORSUMMARY = Menu.FIRST;
    private static final int MENU_STARTORSTOP = Menu.FIRST + 1;
    private static final int MENU_BACK = Menu.FIRST + 2;
    
	
	//private static final String RECORDING_START = "  Start";
	//private static final String RECORDING_STOP  = "  Stop";
	
	private boolean recording;
	private boolean mapmode;
	
	private static final int VIEW_DEFAULT = 0;
	//private static final int VIEW_SATELLITE = 1;
	
	private int viewType;

	private MapView mapView;
	private MyLocationOverlay mMyLocationOverlay;
	private MapController mc;
	private List<Overlay> mapOverlays;

	private TableLayout summaryTbl;
	
	private LocationManager myManager;
	
	private TrackSummary sum;
	private Geocoder geoCoder;
	
	public TrackMapActivity() {
		instance = this;
		
	}

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.trackmap);
        
        viewType = TrackMapActivity.VIEW_DEFAULT;
    
        summaryTbl = (TableLayout) findViewById(R.id.summarytbl);
		summaryTbl.setVisibility(View.INVISIBLE);
        
        	
		mapView = (MapView) findViewById(R.id.mapview);
        mapView.setBuiltInZoomControls(true);
        mapView.setClickable(true);
        mapView.setEnabled(true);
        mapView.setReticleDrawMode(MapView.ReticleDrawMode.DRAW_RETICLE_UNDER);
        
        //get mapOverlays
        mapOverlays = mapView.getOverlays();
        
        // get the map controller
        mc = mapView.getController();
        mMyLocationOverlay = new MyLocationOverlay(this, mapView);
        mapOverlays.add(mMyLocationOverlay);
        mMyLocationOverlay.enableMyLocation();
        mMyLocationOverlay.enableCompass();
        mMyLocationOverlay.runOnFirstFix(
            new Runnable() {
                public void run() {
                    mc.animateTo(mMyLocationOverlay.getMyLocation());
                    mc.setZoom(18);
                }
            });
        
        
        
        myManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        locListener = new MyLocationListener(this.getResources(), myManager, mc, mapOverlays, mMyLocationOverlay, mapView);
        //locListener.startListening();
        //mapOverlays.add(new MyRouteOverlay(mMyLocationOverlay.getMyLocation(), null, 1));
        
        mapOverlays.add(new MyLocationGestureListener(mc));
        
        ImageButton play = (ImageButton) findViewById(R.id.play);
        play.setOnClickListener(new PlayOnClickListener());
        
        ImageButton search = (ImageButton) findViewById(R.id.search);
		search.setOnClickListener(new ActionClickListener(TrackMapActivity.this, History.class));
		
		Button save = (Button) findViewById(R.id.save);
		save.setOnClickListener(new SaveClickListener());
		
		mapmode = true;
	}
	
	private class ActionClickListener implements OnClickListener {
		private Class target;
		private Context source;
		
		public ActionClickListener(Context source, Class target){
			this.source = source;
			this.target = target;
		}
		
		public void onClick(View v) {
			finish();
			Intent i = new Intent(source, target);
			startActivity(i);
		}
		
	}
    
    private class PlayOnClickListener implements OnClickListener {

		public void onClick(View v) {
			ImageButton play = (ImageButton) v;
			if (!recording) {
				Boolean start = locListener.startListening();
				if (start) {
					
					if(geoCoder == null) {
						geoCoder = new Geocoder(TrackMapActivity.getContext(), Locale
								.getDefault());
					}
					
					mapView.setVisibility(View.VISIBLE);
					summaryTbl.setVisibility(View.INVISIBLE);
					mapView.invalidate();
					recording = true;
					mapmode = true;
					
					if (sum == null) {
						sum = new TrackSummary(locListener.getMyGeopoints(), geoCoder);
					}
					
					sum.refresh();
					//HARDCODED----PARAH....!!!!
					sum.setMode(DatabaseHelper.TABLE_CONSTANT_LIST.ID_PREFERENCE_CAR);
					
					play.setImageResource(R.drawable.stop);
					Toast.makeText(TrackMapActivity.this, "Start tracking...", Toast.LENGTH_LONG).show();
				}
			} else {
				locListener.stopListening();
				recording = false;
				play.setImageResource(R.drawable.play);
				Toast.makeText(TrackMapActivity.this, "Stop tracking", Toast.LENGTH_LONG).show();
				
				
				getSummary();
				mapmode = false;
				//summarize
				/*
				TrackSummary sum = new TrackSummary(locListener.getMyGeopoints());
				sum.summarize();
				AlertDialog.Builder builder = new AlertDialog.Builder(TrackMapActivity.getContext());
				builder.setMessage("Date Start:\t" + sum.getDateStartStr() + "\n"
								 + "Time Start:\t" + sum.getTimeStartStr() + "\n"
								 + "Duration:\t\t" + sum.getTimeSpentStr()+ "\n"
								 + "Distance:\t\t" + sum.getDistanceStr() + "\n"
								 + "Avg Speed:\t" + sum.getAvgSpeedStr() + "\n"
								 + "Min Speed:\t" + sum.getMinSpeedStr() + "\n"
								 + "Max Speed:\t" + sum.getMaxSpeedStr() + "\n")
				       .setCancelable(false)
				       .setPositiveButton("OK", new DialogInterface.OnClickListener() {
				           public void onClick(DialogInterface dialog, int id) {
				                dialog.dismiss();
				           }
				       });
				AlertDialog alert = builder.create();
				alert.show();
				*/
			}
		}
    }

    private class SaveClickListener implements OnClickListener {

		public void onClick(View v) {
			TextView tv = (TextView) findViewById(R.id.title);
			sum.setTitle(tv.getText().toString());
			
			long result = TrackSummaryDB.save(sum);
			
			summaryTbl.setVisibility(View.INVISIBLE);
			mapView.setVisibility(View.VISIBLE);
			mapmode = true;
		}
    }
    
    private void getSummary(){

    	//TrackSummary sum = new TrackSummary(locListener.getMyGeopoints());
		sum.summarize();
		
    	mapView.setVisibility(View.INVISIBLE);
		summaryTbl.setVisibility(View.VISIBLE);
    	TextView tv;
    	
    	tv = (TextView) this.findViewById(R.id.title);
    	tv.setText(sum.getTitle());
    	
    	tv = (TextView) this.findViewById(R.id.starttime);
    	tv.setText(sum.getTimeStartStr());
    	
    	tv = (TextView) this.findViewById(R.id.duration);
    	tv.setText(sum.getTimeSpentStr());
    	
    	tv = (TextView) this.findViewById(R.id.distance);
    	tv.setText(sum.getDistanceStr());
    	
    	tv = (TextView) this.findViewById(R.id.min);
    	tv.setText(sum.getMinSpeedStr());
    	
    	tv = (TextView) this.findViewById(R.id.avg);
    	tv.setText(sum.getMinSpeedStr());
    	
    	tv = (TextView) this.findViewById(R.id.max);
    	tv.setText(sum.getMaxSpeedStr());
    	
    }
    
    private void buildMenu(Menu menu){
    		if (mapmode) {
    			menu.add(0, MENU_MAPORSUMMARY, 0, "Summary")
    			.setIcon(android.R.drawable.ic_menu_day);
    		}else {
    			menu.add(0, MENU_MAPORSUMMARY, 0, "Map")
    			.setIcon(android.R.drawable.ic_menu_day);
    		}
    		
           if (recording) {
           		menu.add(0, MENU_STARTORSTOP, 1, "Stop")
           		.setIcon(android.R.drawable.ic_menu_myplaces);
           }else {
        	   menu.add(0, MENU_STARTORSTOP, 1, "Start")
           		.setIcon(android.R.drawable.ic_menu_myplaces);
           }
           
           menu.add(0, MENU_BACK, 2, "Back")
           .setIcon(android.R.drawable.ic_menu_close_clear_cancel);

    }
    
    public boolean onPrepareOptionsMenu(Menu menu){
    	menu.clear();
    	buildMenu(menu);
    	
    	return true;
    }
    
	public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        
        buildMenu(menu);
     
        return true;
		
    }
	
	/**
	 * @see com.google.android.maps.MapActivity#onPause()
	 */
	@Override
	public void onPause() {
		super.onPause();
		if (!recording) {
			mMyLocationOverlay.disableMyLocation();
			myManager.removeUpdates(locListener);
		}
	}

	/**
	 * @see com.google.android.maps.MapActivity#onResume()
	 */
	@Override
	public void onResume() {
		super.onResume();
		if (!recording) {
			mMyLocationOverlay.enableMyLocation();
		} else {
			locListener.startListening();
		}
	}
    
	/*
    private class ToggleViewHandler implements View.OnClickListener {
    	public void onClick(View v){
    		
    		MapView mapView = (MapView) findViewById(R.id.mapview);
            
    		switch(viewType) {
	    		case TrackMapActivity.VIEW_DEFAULT:
	    			viewType = TrackMapActivity.VIEW_SATELLITE;
	    			mapView.setSatellite(true);
	    	        //mapView.setStreetView(true);
	    			break;
	    		case TrackMapActivity.VIEW_SATELLITE:
	    			viewType = TrackMapActivity.VIEW_DEFAULT;
	    			mapView.setSatellite(false);
	    			//mapView.setStreetView(false);
	    			break;
	    		}
    		
    	}
    }
    
    private class ResultClickHandler implements View.OnClickListener {
		public void onClick(View v) {
			//showDialog(Start.DIALOG_OPTIONS);
			Intent i = new Intent(TrackMapActivity.this, Finish.class);
			startActivity(i);//, Global.ACTIVITY_FINISH);
			
		}
	}
    
    private class RecordClickHandler implements View.OnClickListener {
		public void onClick(View v) {
			
			if (recording) {
				new AlertDialog.Builder(TrackMapActivity.this).setIcon(
						android.R.drawable.ic_dialog_alert)
						.setTitle("Recording")
						.setMessage("You are about to stop recording. Are you sure?")
						.setPositiveButton("Yes",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,int which) {
									
									//stop recording and show result
									Intent i = new Intent(TrackMapActivity.this, Finish.class);
									startActivity(i);//, Global.ACTIVITY_FINISH);
									
									Button btn = (Button) TrackMapActivity.this.findViewById(R.id.record);
									btn.setText(TrackMapActivity.RECORDING_START);
									
									recording = !recording;											
								}
							})
						.setNegativeButton("No", null).show();
				
				
			}else {
				Button btn = (Button) v;
				btn.setText(TrackMapActivity.RECORDING_STOP);
				recording = !recording;
			}
			
			
		}
	}
    */

	/*
    protected Dialog onCreateDialog(int id){
		switch(id) {
		case TrackMapActivity.DIALOG_OPTIONS:
			return new ListMenu(this, new OptionsListener(), options);
		}
		return null;
	}
    */
	/*
    private class OptionsListener implements ListMenu.ListMenuListener {
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			Log.d("TEST INDEX: ", "INDEX: " + arg2);
			if (arg2 == 0) {
				//START
				if (!recording) {
					Boolean start = locListener.startListening();
					if (start) {
						mapView.invalidate();
						recording = true;
					
						((PopMenu)arg0.getAdapter().getItem(0)).setMenuText(RECORDING_STOP);
						((ListView)arg0).invalidateViews();
						
						Toast.makeText(TrackMapActivity.this, "Start tracking...", Toast.LENGTH_LONG).show();
					}
				} else {
					locListener.stopListening();
					recording = false;
					
					((PopMenu)arg0.getAdapter().getItem(0)).setMenuText(RECORDING_START);
					((ListView)arg0).invalidateViews();
					
					Toast.makeText(TrackMapActivity.this, "Stop tracking", Toast.LENGTH_LONG).show();
				}
			} else if (arg2 == 5){
				locListener.stopListening();
				finish();
			}
		}
    }
    */
    
    
    @Override
    protected boolean isRouteDisplayed() {
        return true;
    }
    
    public static Context getContext() {
    	return instance;
    }
}